package com.heima.wemedia.listener;

import com.heima.api.feign.ApArticleFeignClient;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.constants.WmNewsMessageConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * TODO
 *
 * @Author mr.wu
 * @Data #{DATE} #{TIME}
 */
@Component
@Slf4j
public class WmDelayMessageListener {

    @Autowired
    private  WmNewsService wmNewsService;
    @Autowired
    private  ApArticleFeignClient apArticleFeignClient;
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private WmChannelMapper wmChannelMapper;
    @Autowired
    private WmUserMapper wmUserMapper;





    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = WmNewsMessageConstants.DELAY_ORDER_QUEUE_NAME),
            exchange = @Exchange(name = WmNewsMessageConstants.DELAY_EXCHANGE_NAME, delayed = "true"),
            key = WmNewsMessageConstants.DELAY_ORDER_KEY
    ))
    public void createWmDelayListener(Integer wmNewsId){
        WmNews wmNew = wmNewsMapper.selectById(wmNewsId);
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNew, dto);
        dto.setAuthorId(Long.valueOf(wmNew.getUserId()));
        WmUser user = wmUserMapper.selectById(wmNew.getUserId());
        if(user==null){
            throw new RuntimeException("该用户不存在");
        }
        dto.setAuthorName(user.getName());
        WmChannel wmChannel = wmChannelMapper.selectById(wmNew.getChannelId());
        if(wmChannel==null){
            throw new RuntimeException("该频道不存在");
        }
        dto.setChannelName(wmChannel.getName());
        dto.setLayout(wmNew.getType());
        dto.setFlag((byte) 0);
        dto.setCreatedTime(new Date(System.currentTimeMillis()));
        ResponseResult save = apArticleFeignClient.save(dto);
        Integer code = save.getCode();
        if(code!=200){
            throw  new RuntimeException("保存文章失败");
        }
        wmNew.setArticleId(Long.valueOf(String.valueOf(save.getData())));
        wmNewsService.updateById(wmNew);
        log.info("修改文章状态成功");
    }
}
